//
//  File.swift
//  
//
//  Created by tgy on 2024/8/10.
//

import Foundation
import CLwIP
import NIO

// 定义接受新的连接的回调函数
func np_tcp_accept_callback(arg: UnsafeMutableRawPointer?, newpcb: UnsafeMutablePointer<tcp_pcb>?, err: err_t) -> err_t {
    if let pcb = newpcb {
        // 在这里处理新的连接
        print("New connection accepted: \(pcb)")
    }
    return err_t(ERR_OK.rawValue)
}

// 定义接收数据的回调函数
func np_tcp_recv_callback(arg: UnsafeMutableRawPointer?, tpcb: UnsafeMutablePointer<tcp_pcb>?, p: UnsafeMutablePointer<pbuf>?, err: err_t) -> err_t {
    if let pcb = tpcb, let pbuf = p {
        // 处理接收到的数据
        let pbufStruct = pbuf.pointee
        let data = ByteBufferAllocator().buffer(bytes: Data(bytes: pbufStruct.payload, count: Int(pbufStruct.len)))
        print("Data received: \(data)")
    }
    return err_t(ERR_OK.rawValue)
}

func np_udp_recv(rg: UnsafeMutableRawPointer?, upcb: UnsafeMutablePointer<udp_pcb>?, p: UnsafeMutablePointer<pbuf>?, addr: UnsafePointer<ip_addr_t>?, port: u16_t) {
  if (p != nil) {
      /* send received packet back to sender */
      udp_send(upcb, p);
      /* free the pbuf */
      pbuf_free(p);
  }
}

func np_netif_output( p: UnsafeMutablePointer<pbuf>?, is_ipv4: Bool) -> err_t {
//    let data = ByteBufferAllocator().buffer(bytes: Data(bytes: p?.pointee.payload, count: p?.pointee.len))
//    NEP
//    let packet = [[NEPacket alloc] initWithData:data protocolFamily:(is_ipv4 ? AF_INET : AF_INET6)];
//    NSArray* packets = [NSArray arrayWithObject:packet];
//
//    NPPacketTunnelHandler.shared.output(packets);
    
    return err_t(ERR_OK.rawValue)
}

func np_netif_linkoutput( p: UnsafeMutablePointer<pbuf>?, is_ipv4: Bool) -> err_t {
//    let data = ByteBufferAllocator().buffer(bytes: Data(bytes: p?.pointee.payload, count: p?.pointee.len))
//    NEP
//    let packet = [[NEPacket alloc] initWithData:data protocolFamily:(is_ipv4 ? AF_INET : AF_INET6)];
//    NSArray* packets = [NSArray arrayWithObject:packet];
//
//    NPPacketTunnelHandler.shared.output(packets);
    
    return err_t(ERR_OK.rawValue)
}

func np_netif_output (netif: UnsafeMutablePointer<netif>?, p: UnsafeMutablePointer<pbuf>?, ipaddr: UnsafePointer<ip4_addr_t>?) -> err_t {
    return np_netif_output(p: p, is_ipv4: true);
}

func np_netif_output_v6 (netif: UnsafeMutablePointer<netif>?, p: UnsafeMutablePointer<pbuf>?, ipaddr: UnsafePointer<ip6_addr_t>?) -> err_t {
    return np_netif_output(p: p, is_ipv4: false);
}

func np_netif_init(netif: UnsafeMutablePointer<netif>?) -> err_t {
    netif?.pointee.output = np_netif_output
    netif?.pointee.output_ip6 = np_netif_output_v6
    return err_t(ERR_OK.rawValue)
}

/**
 通过IP头获取协议版本号
 */
func ipHdrGetVersion(_ payload: UnsafeMutableRawPointer) -> Int {
    let byte = payload.load(as: UInt8.self)
    return Int(byte >> 4)
}
